import { onUnmounted, ref } from 'vue'

export function useSpeechSynthesis() {
  const speaking = ref(false)

  const speak = (text: string, lang = 'zh-CN') => {
    if (!window.speechSynthesis) return
    const utterance = new SpeechSynthesisUtterance(text)
    utterance.lang = lang
    utterance.onstart = () => (speaking.value = true)
    utterance.onend = () => (speaking.value = false)
    speechSynthesis.speak(utterance)
  }

  const cancel = () => {
    window.speechSynthesis.cancel()
    speaking.value = false
  }

  onUnmounted(cancel)

  return { speak, cancel, speaking }
}
